package cn.kpt.biz.interceptor;


import cn.kpt.beans.dto.Dto;
import cn.kpt.utils.DtoUtil;
import cn.kpt.utils.ErrorCode;
import cn.kpt.utils.ValidationToken;
import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private ValidationToken validationToken;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(validationToken.getCurrentUser("token:"+token) == null){
            Dto dto = DtoUtil.returnFail("用户还未登录或登录已经过期！", ErrorCode.AUTH_TOKEN_INVALID);
            response.getWriter().print(JSON.toJSONString(dto));
            return false;
        }
        return true;
    }
}
